<template>
  <div class="clearfix">
    <div style="display: flex; flex-wrap: wrap; width: 600px">
      <a-upload
        action=""
        list-type="picture-card"
        :default-file-list="fileList"
        :file-list="fileList"
        :before-upload="beforeUpload"
        :remove="handleRemove"
        @preview="handlePreview"
      >
        <div v-if="fileList && fileList.length < imageCount">
          <plus-outlined />
          <div class="ant-upload-text">Upload</div>
        </div>
      </a-upload>
      <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
        <img alt="example" style="width: 100%" :src="previewImage" />
      </a-modal>
    </div>
  </div>
</template>
<script lang="ts">
import { PlusOutlined } from '@ant-design/icons-vue'
import { defineComponent, ref } from 'vue'
import common from '@/api/common'

interface FileItem {
  uid: string
  name?: string
  status?: string
  response?: string
  percent?: number
  url?: string
  preview?: string
  originFileObj?: any
}

export default defineComponent({
  components: {
    PlusOutlined
  },
  props: {
    imageCount: { type: Number, default: 10 },
    fileList: {
      type: Array,
      default() {
        return []
      }
    }
  },
  emits: ['editFile'],
  setup(props: any, content) {
    const previewVisible = ref<boolean>(false)
    const previewImage = ref<string | undefined>('')
    const handleCancel = () => {
      previewVisible.value = false
    }
    const handlePreview = async (file: FileItem) => {
      previewImage.value = file.url || file.preview
      previewVisible.value = true
    }
    // 上传图片
    const handleUpload = (file: FileItem) => {
      const formData = new FormData()
      formData.append('file', file as any)
      formData.append('fileType', '12')
      common.uploadFile(formData).then((res) => {
        const url: string = res.data.imageSite + res.data.imagePath
        const newFileList = (props.fileList as FileItem[]).slice()
        newFileList.push({ uid: url, url })
        content.emit('editFile', newFileList)
      })
    }
    /**
     * 移除图片
     * params {FileItem} file 图片数值
     */
    const handleRemove = (file: FileItem) => {
      const index = (props.fileList as FileItem[]).indexOf(file)
      const newFileList = (props.fileList as FileItem[]).slice()
      newFileList.splice(index, 1)
      content.emit('editFile', newFileList)
    }
    const beforeUpload = (file: FileItem) => {
      handleUpload(file)
      return false
    }
    return {
      previewVisible,
      previewImage,
      // fileList,
      handleCancel,
      handlePreview,
      beforeUpload,
      handleRemove
    }
  }
})
</script>
<style>
/* you can make up upload button and sample style by using stylesheets */
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
